﻿$(function($) {
	/*case"system_struts":添加母线
						 case"component_threeTransformer"://添加总压侧
						 case"component_transformer":
						 case"component_bus":
						 case"component_lowbus":
						 case"component_lowbus_breaker":
						 case"component_converge":
						 case"component_gen":
						 case"component_inverter":
                         */

	// var contextMenu = $("#component_threeTransformer_menu").jqxMenu({ width: 200,   autoOpenPopup: false, mode: 'popup',theme:theme,popupZIndex: 999999 });
	// var contextMenu = $("#component_transformer_menu").jqxMenu({ width: 200,   autoOpenPopup: false, mode: 'popup',theme:theme,popupZIndex: 999999 });
	// var contextMenu = $("#component_bus_menu").jqxMenu({ width: 200,   autoOpenPopup: false, mode: 'popup',theme:theme,popupZIndex: 999999 });
	// var contextMenu = $("#component_lowbus_menu").jqxMenu({ width: 200,   autoOpenPopup: false, mode: 'popup',theme:theme,popupZIndex: 999999 });


	$("#struts_tree").on('mousedown', function(event) {


		var rightClick = isRightClick(event) || $.jqx.mobile.isTouchDevice();

		if (rightClick) {
			var scrollTop = $(window).scrollTop();
			var scrollLeft = $(window).scrollLeft();

			$("#system_struts_menu").jqxMenu('open', parseInt(event.clientX) + 5 + scrollLeft, parseInt(event.clientY) + 5 + scrollTop);

			return false;
		}

	});

});

//===============添加设备对话框
//系统默认添加--单母-单主变-低压母线-单集电线-单机组结构
//--系统结构》添加高压母线
//--母线》添加主变
//--主变》添加低压母线
//--低压母线》添加集电线
//
//

function initEquDlg(treewidget) {
	var loadDlgContent = function() {

		var url = "table_xml/SystemTopology.xml";
		// prepare the data
		//加载配置文件
		var dataAdapter = new $.jqx.dataAdapter(tableSource(url), {
			loadComplete: function() {
				// get data records.
				var records = dataAdapter.records;
				var length = records.length;
				var propertyEdit = $('<table></table').appendTo("#add_equ_dlg_content");

				for (var i = 0; i < length; i++) {
					var record = records[i];
					var propertyEditItem = $('<tr style="height:30px"></tr>').appendTo(propertyEdit);
					var desc = $('<td style="width:80px" ></td>').html(record.Desc).appendTo(propertyEditItem);
					var valitem = $("<td></td>").appendTo(propertyEditItem);

					//如果是枚举类型数据，获取枚举量，并形添加枚举值到droplist提供选择
					if (record.DataType != "Enum") {

						var value = $('<input   class="property_value" />').attr("id", $.trim(record.Field)).val(record.DefaultValue).appendTo(valitem);

						value.jqxInput({
							placeHolder: "",
							height: 22,
							width: 95,
							minLength: 1,
							disabled: record.Field.indexOf("EqptName") < 0 ? true : false
						});


					} else if (record.Field == "EqptType") {

						var combo = $('<div   class="property_comb"  class="z-index:9999"></div>').attr("id", $.trim(record.Field)).appendTo(valitem);
						var combodata = [];

						combo.jqxDropDownList({
							source: getComponentList(),
							theme: theme,
							placeHolder: "选择设备：",
							displayMember: 'typeName',
							valueMember: 'typeId',
							width: 95,
							height: 20 //,popupZIndex: 999
						});
						var items = $("#add_equ_dlg #EqptType").jqxDropDownList('getItems');


						combo.on('change', function(event) {
							var args = event.args;
							if (args) {
								// index represents the item's index.                      
								var index = args.index;
								var item = args.item;
								// get item's label and value.
								var label = item.label;
								$("#add_equ_dlg #EqptName").jqxInput('val', label);
							}
						});



					}
				}
			}

		});
		dataAdapter.dataBind();
		$(".dlg_btn").jqxButton({
			width: 50,
			height: 20,
			theme: theme
		});
	};
	//添加设备对话框 对话框下面的 jqxDropDownList，需要取 host。parent的zindex作为自己的index，所以在这里需要设置对话框的zindex
	$("#add_equ_dlg").css("z-index", 999).jqxWindow({
		width: 210,
		height: 270,
		title: "添加设备",
		theme: theme,
		resizable: false,
		isModal: true,
		autoOpen: false,
		okButton: $('#Ok'),
		cancelButton: $("#Cancel"),
		modalZIndex: 900,
		initContent: loadDlgContent()
	}).on('close', function(event) {
		var eventData = "";
		if (event.type === 'close') {
			eventData += ', Dialog result: ';
			if (event.args.dialogResult.OK) {

				eventData += 'OK';
				var EqptId = parseInt($("#add_equ_dlg #EqptId").jqxInput('val')); // EqptId 已经设置为内部的uid了 ，不能改变 treegrid内部的uid的类型
				var EqptName = $("#add_equ_dlg #EqptName").jqxInput('val');
				var PhyscPid = $("#add_equ_dlg #PhyscPid").jqxInput('val');
				var LogicPid = $("#add_equ_dlg #LogicPid").jqxInput('val');
				var EqptType = $("#add_equ_dlg #EqptType").jqxDropDownList('val'); //combo 返回的设备号是从1开始的
				var selection = $(treewidget).jqxTreeGrid('getSelection');
				var rowid = 0;
				var logicId = 0;

				var item = $("#add_equ_dlg #EqptType").jqxDropDownList('getSelectedItem');
				if (selection[0]) {
					rowid = selection[0].uid;

					function getLogicId(select) {
						var logicId = 0;
						if (select.IsLogic) {
							logicId = select.EqptId;
						} else {
							if (select.parent) {
								logicId = getLogicId(select.parent);
							} else {
								logicId = 0;
							}
						}
						return logicId;
					}
					logicId = getLogicId(selection[0]);
				}
				//alert(EqptType);
				//如果logic和physcpid都为0 认为是顶层节点
				var parid = ((LogicPid == 0) && (PhyscPid == 0)) ? null : rowid;
				//形成需要添加设备的数据
				var addColumns = [];
				var colum = {};
				colum.EqptId = EqptId;
				colum.EqptName = EqptName;
				colum.PhyscPid = PhyscPid;
				colum.LogicPid = LogicPid;
				colum.EqptType = EqptType;
				addColumns.push(colum);
				if (EqptType == $.config.eqpEnum.TransFormer) {
					var colum = {};
					colum.EqptId = $.config.EqpId.get();
					colum.EqptName = '低压母线';
					colum.PhyscPid = EqptId;
					colum.LogicPid = logicId;
					colum.EqptType = $.config.eqpEnum.NoTopBus;
					addColumns.push(colum);
				}

				//alert(JSON.stringify(addColumns));
				//  else if (EqptType == $.config.eqpEnum.ThreeTransf) {
				// 	var colum = {};
				// 	colum.EqptId = $.config.EqpId.get();
				// 	colum.EqptName = '中压测';
				// 	colum.PhyscPid = EqptId;
				// 	colum.LogicPid = logicId;
				// 	colum.EqptType = $.config.eqpEnum.NoTopBus;
				// 	var colum1 = {};
				// 	colum1.EqptId = $.config.EqpId.get();
				// 	colum1.EqptName = '低压侧';
				// 	colum1.PhyscPid = EqptId;
				// 	colum1.LogicPid = logicId;
				// 	colum1.EqptType = $.config.eqpEnum.NoTopBus;
				// 	addColumns.push(colum);
				// 	addColumns.push(colum1);
				// }

				$.config.postData("defaultData/action/editGens.json", addColumns, function() {
					//其他设备只添加设备本省

					$(treewidget).jqxTreeGrid('addRow', null, {
						EqptName: EqptName,
						EqptId: EqptId,
						PhyscPid: PhyscPid,
						LogicPid: item.originalItem.IsLogic ? LogicPid : '', //非逻辑设备，不需要配置逻辑ID
						EqptType: EqptType,
						IsLogic: item.originalItem.IsLogic //通过originalItem获取原始数据中的IsLoigc标志
					}, 'last', parid);
					$(treewidget).jqxTreeGrid('expandRow', parid);
					// $("#treeGrid").jqxTreeGrid('selectRow', 'ALFKI');
					//变压器下面肯定只有一条低压母线
					if (EqptType == $.config.eqpEnum.TransFormer) {
						var parentId = $(treewidget).data("equ")["newid"];
						$(treewidget).jqxTreeGrid('addRow', null, {
							EqptName: '低压母线',
							EqptId: $.config.EqpId.get(),
							PhyscPid: EqptId,
							LogicPid: logicId, //非逻辑设备，不需要配置逻辑ID
							EqptType: $.config.eqpEnum.NoTopBus,
							IsLogic: true
						}, 'last', parentId);

						//三圈变压器下面有两条母线
					}

					//  else if (EqptType == $.config.eqpEnum.TransFormer) {
					// 	var parentId = $(treewidget).data("equ")["newid"];
					// 	//按照 EqptId 的规则，先添加的为中压母线下面的低压母线。那么中压测的设备号肯定是小于低压侧的设备号。
					// 	$(treewidget).jqxTreeGrid('addRow', null, {
					// 		EqptName: '中压测',
					// 		EqptId: $.config.EqpId.get(),
					// 		PhyscPid: EqptId, //物理伏设备ID就是当前添加的变压器
					// 		LogicPid: logicId, //非逻辑设备，不需要配置逻辑ID
					// 		EqptType: $.config.eqpEnum.NoTopBus,
					// 		IsLogic: true  
					// 	}, 'last', parentId);

					// 	$(treewidget).jqxTreeGrid('addRow', null, {
					// 		EqptName: '低压侧',
					// 		EqptId: $.config.EqpId.get(),
					// 		PhyscPid: EqptId,
					// 		LogicPid: logicId, //非逻辑设备，不需要配置逻辑ID
					// 		EqptType: $.config.eqpEnum.NoTopBus,
					// 		IsLogic: true  
					// 	}, 'last', parentId);
					// }

				});

			} else if (event.args.dialogResult.Cancel) {
				var EqptId = parseInt($("#add_equ_dlg #EqptId").jqxInput('val'));
				$.config.EqpId.remove(EqptId);
				//eventData += 'Cancel';
			} else {
				//eventData += 'None';
			}
		}
	});
}

function showEquDlg(treewidget) {
	$("#add_equ_dlg #EqptId").jqxInput('val', $.config.EqpId.get());
	$("#add_equ_dlg #EqptName").jqxInput('val', draoList[$(treewidget).data("equ")["EqptType"]]);
	$("#add_equ_dlg #PhyscPid").jqxInput('val', $(treewidget).data("equ")["PhyscPid"]);
	$("#add_equ_dlg #LogicPid").jqxInput('val', $(treewidget).data("equ")["LogicPid"]);


	var items = $("#add_equ_dlg #EqptType").jqxDropDownList('getItems');
	//根据父类设备--设置下拉列表的可选项
	//	var log="";
	for (var i = 0; count = items.length, i < count; i++) {
		// log+=items[i].value+"="+items[i].label+"\n";
		if ($(treewidget).data("equ")["EqptType"] == items[i].value) // 只能选择指定设备，除了 变压器可以选择类型
		{
			//alert("en"+items[i].value);
			$("#add_equ_dlg #EqptType").jqxDropDownList('enableItem', items[i].value);
		} else {
			// //如果当添加是变压器，增加3圈变压器的选择
			// if (($(treewidget).data("equ")["EqptType"] == $.config.eqpEnum.TransFormer) && (items[i].value == $.config.eqpEnum.ThreeTransf)) {
			// 	$("#add_equ_dlg #EqptType").jqxDropDownList('enableItem', items[i].value);
			// } else

			$("#add_equ_dlg #EqptType").jqxDropDownList('disableItem', items[i].value);
		}
	}
	$("#add_equ_dlg #EqptType").jqxDropDownList('val', $(treewidget).data("equ")["EqptType"]);
	//alert(log);//"eq"+$(treewidget).data("equ")["EqptType"]);
	$("#add_equ_dlg").jqxWindow("open");
}
// 初始化系统结构编辑的右键菜单处理
function initContextMenu(treewidget) {
	$("#addbus").on("click", function() {
		alert("addbus")
	});

	initEquDlg(treewidget);

	var menuClick = function(event) {
		var target = $(event.target);
		var equval = {};

		var menutype = ""; // 当前菜单点击的是增加，还是删除标志
		var selection = $(treewidget).jqxTreeGrid('getSelection');


		var rowid = 0;
		var equid = 0;
		var logicId = 0;
		//获取当前选择的tree的选择项中的数据
		if (selection[0]) {
			rowid = selection[0].uid;
			equid = selection[0].EqptId;

			function getLogicId(select) {
				var logicId = 0;
				if (select.IsLogic) {
					logicId = select.EqptId;
				} else {
					if (select.parent) {
						logicId = getLogicId(select.parent);
					} else {
						logicId = 0;
					}
				}
				return logicId;
			}
			logicId = getLogicId(selection[0]);

		}
		//通过item-value，路由处理菜单点击事件
		switch (target.attr("item-value")) {
			case "add_bus":
				{
					var rowid = 0;
					$(treewidget).data("equ")["PhyscPid"] = 0;
					$(treewidget).data("equ")["LogicPid"] = logicId;
					$(treewidget).data("equ")["EqptType"] = $.config.eqpEnum.TopBus;
					// alert($.config.eqpEnum.TopBus);
					menutype = "add";
				}
				break;
			case "add_transform":
				{
					$(treewidget).data("equ")["PhyscPid"] = equid;
					$(treewidget).data("equ")["LogicPid"] = '无';
					$(treewidget).data("equ")["EqptType"] = $.config.eqpEnum.TransFormer;
					menutype = "add";
				}
				break;
			// case "add_mid_lowbus":
			// 	{
			// 		$(treewidget).data("equ")["PhyscPid"] = equid;
			// 		$(treewidget).data("equ")["LogicPid"] = logicId;
			// 		$(treewidget).data("equ")["EqptType"] = $.config.eqpEnum.NoTopBus;
			// 		menutype = "add";
			// 	}
			// 	break;
			case "add_lowbus":
				{
					$(treewidget).data("equ")["PhyscPid"] = equid;
					$(treewidget).data("equ")["LogicPid"] = logicId;
					$(treewidget).data("equ")["EqptType"] = $.config.eqpEnum.NoTopBus;
					menutype = "add";
				}
				break;
			case "add_coverge":
				{
					$(treewidget).data("equ")["PhyscPid"] = equid;
					$(treewidget).data("equ")["LogicPid"] = logicId;
					$(treewidget).data("equ")["EqptType"] = $.config.eqpEnum.SetWire;
					menutype = "add";
				}
				break;
			case "delete":
				{
					menutype = "delete";
				}
				break;

			default:


		}
		//alert(bbb.text());//.attr("item-value"));
		if (menutype == "add") {
			showEquDlg(treewidget);
		} else if (menutype == "delete") {
			//从设备库中删除对应的id
			$.config.postData("defaultData/action/editGens.json", {}, function() {
				$.config.EqpId.remove(equid);
				$(treewidget).jqxTreeGrid('deleteRow', rowid);
			});

		}

	};


	var system_struts_menu_source = [{
		label: "添加顶层母线",
		value: "add_bus"
	}];
	var component_bus_menu_source = [{
		label: "添加变压器",
		value: "add_transform"
	}, {
		label: "删除当前设备",
		value: "delete"
	}];
	var component_threeTransformer_menu_source = [{
		// 	label: "添加中压测母线",
		// 	value: "add_mid_lowbus"
		// }, {
		// 	label: "添加低压侧母线",
		// 	value: "add_lowbus"
		// }, {
		label: "删除当前设备",
		value: "delete"
	}];
	var component_transformer_menu_source = [{
			label: "添加低压母线",
			value: "add_lowbus"
		}, {
		label: "删除当前设备",
		value: "delete"
	}];

	$("#system_struts_menu").jqxMenu({
		source: system_struts_menu_source,
		width: 150,
		autoOpenPopup: false,
		mode: 'popup',
		theme: theme,
		popupZIndex: 999999
	}).on('itemclick', menuClick);
	//顶层母线菜单
	$("#component_TopBus_menu").jqxMenu({
		source: component_bus_menu_source,
		width: 150,
		autoOpenPopup: false,
		mode: 'popup',
		theme: theme,
		popupZIndex: 999999
	}).on('itemclick', menuClick);

	// // 三圈变压器
	// $("#component_threeTransformer_menu").jqxMenu({
	// 	source: component_threeTransformer_menu_source,
	// 	width: 150,
	// 	autoOpenPopup: false,
	// 	mode: 'popup',
	// 	theme: theme,
	// 	popupZIndex: 999999
	// }).on('itemclick', menuClick);

	// 普通变压器
	$("#component_TransFormer_menu").jqxMenu({
		source: component_transformer_menu_source,
		width: 150,
		autoOpenPopup: false,
		mode: 'popup',
		theme: theme,
		popupZIndex: 999999
	}).on('itemclick', menuClick);

	var component_lowbus_menu_source = [{
		label: "添加集电线设备",
		value: "add_coverge"
	}, {
		label: "删除当前设备",
		value: "delete"
	}];
	var component_converge_menu_source = [{
		label: "删除当前设备",
		value: "delete"
	}];
	// var component_gen_menu_source = [{
	// 	label: "删除当前设备",
	// 	value: "delete"
	// }];

	// var component_inverter_menu_source = [{
	// 	label: "删除当前设备",
	// 	value: "delete"
	// }];


	$("#component_NoTopBus_menu").jqxMenu({
		source: component_lowbus_menu_source,
		width: 150,
		autoOpenPopup: false,
		mode: 'popup',
		theme: theme,
		popupZIndex: 999900
	}).on('itemclick', menuClick);


	$("#component_SetWire_menu").jqxMenu({
		source: component_converge_menu_source,
		width: 150,
		autoOpenPopup: false,
		mode: 'popup',
		theme: theme,
		popupZIndex: 999900
	}).on('itemclick', menuClick);

	// $("#component_gen_menu").jqxMenu({
	// 	source: component_gen_menu_source,
	// 	width: 150,
	// 	autoOpenPopup: false,
	// 	mode: 'popup',
	// 	theme: theme,
	// 	popupZIndex: 999900
	// }).on('itemclick', menuClick);

	// $("#component_inverter_menu").jqxMenu({
	// 	source: component_inverter_menu_source,
	// 	width: 150,
	// 	autoOpenPopup: false,
	// 	mode: 'popup',
	// 	theme: theme,
	// 	popupZIndex: 999900
	// }).on('itemclick', menuClick);



}

function isRightClick(event) {
	var rightclick;
	if (!event) var event = window.event;
	if (event.which) rightclick = (event.which == 3);
	else if (event.button) rightclick = (event.button == 2);
	return rightclick;
}